<template>
	<view class="driverIndex">
		<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="button" activeColor="#00aded"></uni-segmented-control>
		<view class="content">
			<view class="unreceive" v-show="current === 0">
				<dil-card class="dilCard" @emitEvent="emitEvent" v-bind.sync="options"></dil-card>
			</view>
			<view class="receiving" v-show="current === 1">
				<view class="top" v-if="options.requestQuery.status == '已确认' && rowDataListLength == 1">
					<uni-section title="运单二维码" type="line" titleFontSize="20px">
						<uqrcode ref="uqrcode" canvas-id="qrcode" :value="transOrderNumber" :options="{ margin: 10 }" :size="280" v-if="transOrderNumber != null"></uqrcode>
					</uni-section>
				</view>
				<view class="main" v-if="options.requestQuery.status == '已确认' && rowDataListLength >= 1">
					<uni-section title="运单信息" type="line" titleFontSize="20px">
						<dil-card class="dilCard" @emitEvent="emitEvent" v-bind.sync="options"></dil-card>
					</uni-section>
				</view>
				<view class="floot" v-if="options.requestQuery.status == '已确认' && rowDataListLength == 1">
					<uni-section title="运单实绩" type="line" titleFontSize="20px">
						<dil-step :stepsList="stepList"></dil-step>
					</uni-section>
				</view>
				<view class="notips" v-if="rowDataListLength == 0">
					<text>无正在执行的运单</text>
				</view>
			</view>
		</view>
		<view class="poper">
			<uni-popup ref="poper" type="center" border-radius="10px 10px 0 0" background-color="#fff" style="width: 100%">
				<view class="tip">
					<text style="font-weight: 700">提示</text>
					<text style="font-size: 30rpx; color: #ff0000">请确认运单以下信息</text>
				</view>
				<view class="importData" v-for="(item, index) in importData" :key="index">
					<text v-if="currentItem[item.prop] != null" style="color: #000000">{{ item.label }}</text>
					<text v-if="currentItem[item.prop] != null">{{ currentItem[item.prop] }}</text>
				</view>
				<view class="btn">
					<button type="danger" @click="cancelSign">取消</button>
					<button type="primary" @click="makeSureSign" :disabled="btnDisable">{{ btnMake }}</button>
				</view>
			</uni-popup>
		</view>
		<view class="poperView">
			<uni-popup ref="poperView" :is-mask-click="false" border-radius="10px 10px 0 0" background-color="#fff" style="width: 100vw; height: 100vh">
				<uni-section title="任务汇总" type="line" padding titleColor="#00aded" class="poperView_section">
					<uni-grid :column="3" :showBorder="false" square @change="changeGrid($event)">
						<uni-grid-item :index="index" :key="index" v-for="(item, index) in materialTypeOrderList">
							<view class="grid-item-box" style="background-color: #fff">
								<uni-badge class="uni-badge-left-margin" :text="item.count" absolute="rightTop" :offset="[-3, -3]" size="small">
									<uni-icons custom-prefix="iconfont" type="wlIcon-qiachetou" :size="30" color="#00aded" />
									<text class="text">{{ item.businessName }}</text>
								</uni-badge>
							</view>
						</uni-grid-item>
					</uni-grid>
				</uni-section>
			</uni-popup>
		</view>
		<view class="poper">
			<uni-popup ref="poper" type="center" border-radius="10px 10px 0 0" background-color="#fff" style="width: 100%">
				<view class="tip">
					<text style="font-weight: 700">提示</text>
					<text style="font-size: 30rpx; color: #ff0000">请确认运单以下信息</text>
				</view>
				<view class="importData" v-for="(item, index) in importData" :key="index">
					<text v-if="currentItem[item.prop] != null" style="color: #000000">{{ item.label }}</text>
					<text v-if="currentItem[item.prop] != null">{{ currentItem[item.prop] }}</text>
				</view>
				<view class="btn">
					<button type="danger" @click="cancelScan">取消</button>
					<button type="primary" @click="makeSureSign" :disabled="btnDisable" v-if="dialogType == '签到'">{{ btnMake }}</button>
					<button type="primary" @click="makeSureScan" :disabled="btnDisable" v-else>{{ btnMake }}</button>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
	name: 'driverIndex',
	data() {
		return {
			items: ['任务列表', '正在执行'],
			current: 0,
			//未确认数据
			stepList: [],
			capacityNumber: null,
			jobNumber: null,
			options: {
				requestUrl: '',
				requestQuery: {},
				cardSlotList: [
					{
						label: '签到',
						icon: 'wlIcon-weijiedan',
						emitEvent: 'signInClick',
						noPre: true,
						arguments: {
							confirmReason: '拒绝'
						}
					},
					{
						label: '计次扫描',
						icon: 'scan',
						emitEvent: 'countScan',
						noPre: true,
						arguments: {
							confirmReason: '拒绝'
						}
					},
					{
						label: '作业详情',
						icon: 'eye',
						emitEvent: 'transOrderDetails',
						noPre: '1',
						showCondition: "!['未确认'].includes(item.status)"
					}
				],
				columnDataList: [],
				totalNum: 0,
				rowDataList: []
			},
			importData: [],
			currentItem: {},
			countdown: 3,
			btnMake: '确认',
			btnDisable: true,
			materialTypeOrderList: [],
			transOrderBusinessName: null,
			qrCodeContent: null,
			dialogType: '签到'
		};
	},
	props: {
		driverTime: {
			type: String,
			default: null
		}
	},
	watch: {
		current: {
			handler(newVal, oldVal) {
				if (newVal == 1) {
					this.getTransOrder({
						jobNumber: this.jobNumber,
						status: '已确认',
						capacityNumber: this.capacityNumber
					});
				} else {
					this.getTransOrder({
						jobNumber: this.jobNumber,
						status: '未确认',
						capacityNumber: this.capacityNumber
					});
				}
			},
			deep: true,
			immediate: false
		},
		driverTime(val) {
			this.getTransOrder({
				jobNumber: this.jobNumber,
				status: '已确认',
				capacityNumber: this.capacityNumber
			});
			this.getTransOrder({
				jobNumber: this.jobNumber,
				status: '未确认',
				capacityNumber: this.capacityNumber
			});
		},
		showResult(val) {
			if (val) {
				this.getTransResult();
			}
		}
		// transOrderId(val) {
		// 	if (val ) {
		// 		this.getTransResult();
		// 	}
		// }
	},

	created() {
		//判断是否车牌号还是手机号
		console.log(uni.getStorageSync('userName').toString(), '1111');
		let userName = uni.getStorageSync('userName').toString();
		let regex = /^1[3-9]\d{9}$/;
		if (regex.test(userName)) {
			this.jobNumber = userName;
		} else {
			this.capacityNumber = userName;
		}
	},
	mounted() {
		this.getTransOrderByJobNumber();
		// this.$refs.poperView.open();
		// this.getReceivedTransOrder();
		this.getIdCardCode();
	},
	computed: {
		transOrderNumber: {
			get() {
				if (this.options.rowDataList.length == 1) {
					return this.options.rowDataList[0].transOrderNumber;
				} else {
					return null;
				}
			},
			set(val) {}
		},
		transOrderId: {
			get() {
				if (this.options.rowDataList.length == 1) {
					return this.options.rowDataList[0].transOrderId;
				} else {
					return null;
				}
			},
			set(val) {}
		},
		rowDataListLength() {
			return this.options.rowDataList.length;
		},
		showResult() {
			if (this.options.requestQuery.status == '已确认' && this.rowDataListLength == 1) {
				return true;
			} else {
				return false;
			}
		}
	},
	methods: {
		countScan(item) {
			let that = this;
			that.$commonScan(async (data) => {
				let scanResult = data.scanResult;
				that.qrCodeContent = scanResult;
				that.importData = item.importData;
				that.currentItem = item;
				that.changeBtnMake();
				that.dialogType = '计次';
				that.$refs.poper.open();
			});
		},
		cancelScan() {
			this.$refs.poper.close();
			this.importData = [];
			this.currentItem = {};
			this.qrCodeContent = null;
		},
		async makeSureScan() {
			let that = this;
			that.Tool.getAddress({ loading: true }, async (data) => {
				if (data.errCode == '10010') {
					uni.showToast({
						title: '获取定位失败,请检查定位设置',
						icon: 'none',
						duration: 2000
					});
				} else {
					let item = that.currentItem;
					item.loadAddress = data.address;
					item.qrCodeContent = that.qrCodeContent;
					item.countMode = '二维码计次';
					item.driverPhone = uni.getStorageSync('userName');
					const res = await this.$myRequest({
						url: '/api/v1/tms/updCountResult',
						data: item
					}).catch((e) => {
						uni.showToast({
							title: e,
							icon: 'none',
							duration: 2000
						});
					});
					if (res.data.status == 'succeed') {
						uni.showToast({
							title: res.data.message,
							icon: 'success',
							duration: 3000
						});
						this.$refs.poper.close();
						this.importData = [];
						this.currentItem = {};
						this.getTransOrderByJobNumber();
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 2000
						});
					}
				}
			});
		},
		changeGrid(event) {
			this.transOrderBusinessName = this.materialTypeOrderList[event.detail.index].businessName;
			this.getReceivedTransOrder();
			this.$refs.poperView.close();
		},
		async getTransOrderByJobNumber() {
			const res = await this.$myRequest({
				url: '/api/v1/uc/getTransOrderByJobNumber',
				data: {
					jobNumber: this.jobNumber
				}
			}).catch(() => {
				this.getReceivedTransOrder();
			});
			if (res.data.data.length <= 1) {
				this.getReceivedTransOrder();
			} else {
				this.materialTypeOrderList = res.data.data;
				this.$refs.poperView.open();
			}
			console.log(res.data.data, 'data');
		},
		cancelSign() {
			this.$refs.poper.close();
			this.importData = [];
			this.cardItem = {};
		},
		makeSureSign() {
			this.signIn(this.currentItem);
		},
		//作业详情
		transOrderDetails(cardItem) {
			cardItem.apiId = 665;
			this.updateTransOrderItem(cardItem);
			uni.navigateTo({
				url: '/pages/transOrder/transOrderDetail'
			});
		},
		//获取司机内码
		async getIdCardCode() {
			if (this.jobNumber == null) {
				uni.showToast({
					duration: 3000,
					title: '使用车牌号登录,请立即绑定身份证',
					icon: 'none'
				});
				return;
			}
			const res = await this.$myRequest({
				url: '/api/v1/uc/getIdCardCode',
				data: {
					jobNumber: this.jobNumber
				}
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.status == 'succeed') {
				console.log(res.data.data, 'res');
				if (res.data.data == null) {
					uni.showToast({
						duration: 3000,
						title: '暂无内码,请立即联系保安或承运单位激活',
						icon: 'none'
					});
				}
			}
		},
		//司机获取是否有正在执行的订单
		async getReceivedTransOrder() {
			const res = await this.$myRequest({
				url: '/api/v1/uc/getReceivedTransOrder',
				data: {
					jobNumber: this.jobNumber,
					capacityNumber: this.capacityNumber,
					transOrderBusinessName: this.transOrderBusinessName
				}
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.data.length > 0) {
				this.current = 1;
			} else {
				this.current = 0;
				this.getTransOrder({
					jobNumber: this.jobNumber,
					status: '未确认',
					capacityNumber: this.capacityNumber
				});
			}
		},
		onClickItem(e) {
			if (this.current != e.currentIndex) {
				this.current = e.currentIndex;
			}
		},
		//获取运单
		async getTransOrder(data = {}) {
			data.transOrderBusinessName = this.transOrderBusinessName;
			this.options.requestUrl = '/api/v1/tms/getTransOrderList?apiId=627';
			this.options.requestQuery = { ...data };
		},
		onSearch(item) {
			this.getOrderSectionDebounce(item);
		},
		async getTransResult() {
			const res = await this.$myRequest({
				url: '/api/v1/tms/getTransResult',
				data: { transOrderId: this.transOrderId }
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			this.stepList = res.data.data;
		},
		emitEvent(eventName, cardItem) {
			this[eventName](cardItem);
		},
		//签到
		// 货车签到
		signIn(cardItem) {
			this.Tool.getAddress({ loading: true }, async (data) => {
				console.log('data: ', data);
				if (data.errCode == '10010') {
					uni.showToast({
						title: '获取定位失败,请检查定位设置',
						icon: 'none',
						duration: 2000
					});
				} else {
					data.transOrderNumber = cardItem.transOrderNumber;
					data.signInMode = '物流签到';
					data.signInAddress = data.address;
					const res = await this.$myRequest({
						url: '/api/v1/tms/signIn',
						data: data
					}).catch((e) => {
						uni.showToast({
							title: e,
							icon: 'none',
							duration: 2000
						});
					});
					if (res.data.status == 'succeed') {
						uni.showToast({
							title: res.data.message,
							icon: 'success',
							duration: 2000
						});
						this.current = 1;
						this.$refs.poper.close();
						this.importData = [];
						this.cardItem = {};
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 2000
						});
					}
				}
			});
		},
		async receiptOrder(data) {
			const res = await this.$myRequest({
				url: '/api/v1/tms/receiptOrder',
				data: data
			}).catch((err) => {
				uni.showToast({
					duration: 2000,
					title: err,
					icon: 'error'
				});
			});
			if (res.data.status == 'succeed') {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'success'
				});
				if (data.confirmReason == '同意') {
					this.current = 1;
				}
			} else {
				uni.showToast({
					title: res.data.message,
					duration: 2000,
					icon: 'error'
				});
			}
		},
		receiveOrder(data) {
			let that = this;
			uni.showModal({
				cancelText: '取消',
				confirmText: '确认',
				title: '提示',
				content: '确定是否接单',
				success: (res) => {
					if (res.confirm) {
						console.log('确认接单');
						that.receiptOrder(data);
					} else if (res.cancel) {
						uni.showToast({
							title: '用户取消操作！',
							icon: 'none',
							duration: 3000
						});
					}
				}
			});
		},
		refuseOrder(data) {
			uni.showModal({
				cancelText: '取消',
				confirmText: '确认',
				title: '提示',
				content: '确定是否拒绝订单',
				editable: true,
				placeholderText: '拒绝理由,必填',
				success: (res) => {
					if (res.confirm) {
						if (res.content) {
							console.log('确认拒单');
							data.refuseReason = res.content;
							that.receiptOrder(data);
						} else {
							uni.showToast({
								title: '拒绝理由,必填',
								duration: 2000,
								icon: 'error'
							});
						}
					} else {
						uni.showToast({
							title: '用户取消操作',
							duration: 1000,
							icon: 'info'
						});
					}
				}
			});
		},
		changeBtnMake() {
			let timer = null;
			let that = this;
			that.countdown = 3;
			this.btnDisable = true;
			timer = setInterval(() => {
				that.btnMake = `确认(${that.countdown--})`;
				if (that.countdown == 0) {
					that.btnMake = `确认`;
					that.btnDisable = false;
					clearInterval(timer);
				}
			}, 1000);
		},
		signInClick(data) {
			this.importData = data.importData;
			this.currentItem = data;
			this.changeBtnMake();
			this.dialogType = '签到';
			this.$refs.poper.open();
		},
		//vuex模块
		...mapMutations('common', ['updateTransOrderItem'])
	}
};
</script>

<style lang="scss" scoped>
.driverIndex {
	width: 100vw;
	height: 100%;
	background-color: #f5f5f5;
	.content {
		.unreceive {
		}
		.receiving {
			.top {
				width: 100vw;
				height: 100%;
				.uni-section {
					width: 100vw;
					/deep/.uni-section-content {
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}
			}
			.main {
				margin-top: 20rpx;
			}
			.floot {
				width: 100vw;
				background-color: #fff;
				// border: 1px solid #000;
				margin-top: 20rpx;
				margin-bottom: 20rpx;
				border-radius: 20rpx;
			}
			.notips {
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 80rpx;
				font-weight: 700;
				height: 500rpx;
			}
		}
	}
	.poper {
		width: 100%;
		.tip {
			font-size: 36rpx;
			font-weight: 500;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			text {
				margin-top: 20rpx;
			}
		}
		.importData {
			margin-top: 20rpx;
			font-size: 38rpx;
			font-weight: 700;
			color: #ff0000;
			text {
				padding: 20rpx;
			}
		}
		.btn {
			margin-top: 30rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin-bottom: 20rpx;
		}
	}
	.poperView {
		// display: flex;
		// justify-content: center;
		// align-items: center;
		&_section {
			margin-top: 20rpx;
			width: 100vw;
			height: 50vh;
			min-height: 240rpx;

			.grid-item-box {
				flex: 1;
				// position: relative;
				/* #ifndef APP-NVUE */
				display: flex;
				/* #endif */
				flex-direction: column;
				align-items: center;
				justify-content: center;
				// padding: 15px 0;
				.uni-badge-left-margin {
					flex: none;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					.text {
						margin-top: 20rpx;
						color: #ff0000;
						font-size: 30rpx;
						font-weight: 500;
					}
				}
			}
		}
	}
}
</style>
